package com.tuo51.partner.controller;


import com.tuo51.core.domain.staffs.Staff;
import com.tuo51.core.service.StaffService;
import com.tuo51.evaluate.domain.childrens.Children;
import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Record;
import com.tuo51.evaluate.service.ChildrenService;
import com.tuo51.evaluate.service.EvaluateV2Service;
import com.tuo51.evaluate.vo.evaluate.EvaluateV2RecordVO;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.StatusResponse;
import com.tuo51.foudation.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.tuo51.foudation.constant.RequestConstant.*;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 测评小程序使用的接口
 */

@RestController
@RequestMapping("/partner/org")
@Api(value = "/partner/org", tags = "伙伴接口 - 机构")
public class PartnerOrgnizationController {

    @Autowired
    private EvaluateV2Service evaluateService;

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private StaffService staffService;

//            3. 家长订单和你们的测试报告建立关系；
//              当家长订单发生支付，并且测评师已经确认接受后，会请求你们接口，预先获取一个测试报告ID，跟订单建立绑定关系。
//              建立关系的测评单都是已付费，业务结果存在家长到店后没有使用测评工具的情况会忽略保持已付费，但是需要区分是否已经有测评报告

    @RequestMapping(value = "/add_evaluate", method = POST)
    @ApiOperation(value = "开始测评")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "formData", name = "pUserId", value = "测评师在系统内id（pUserId）", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "formData", name = "childrenId", value = "宝宝id", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "formData", name = "guardianPhone", value = "监护人电话", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "formData", name = "guardianName", value = "监护人名字", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "formData", name = "guardianRelation", value = "监护人关系", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "formData", name = "weight", value = "体重，单位KG，可float化的字符串", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "formData", name = "height", value = "身高，单位CM，可float化的字符串", required = true, dataType = "string")
    })
    public StatusResponse addEvaluate(@RequestHeader(PARTNERID_KEY) String partner,
                                      @RequestHeader(AUTH_KEY) String auth,
                                      @RequestHeader(REQ_UUID_KEY) String uuid,
                                      @RequestHeader(COMP_VERSION_KEY) String compver,
                                      String pUserId,
                                      String childrenId,
                                      String weight, String height,
                                      String guardianPhone, String guardianName, String guardianRelation){

        Staff staff = staffService.maUserByPartnerUserId(pUserId);
        if (staff == null){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "员工不存在");
        }

        Children children = childrenService.getById(childrenId);
        if (children == null){
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
        }

        children = childrenService.edit(children, null, null, null, guardianPhone,guardianName, guardianRelation,
                null, null, null, null, null, null, null);

        EvaluateV2Record record = evaluateService.startEvaluate(staff.getId(), children, weight, height, false, 0,guardianPhone,guardianRelation);
        evaluateService.payEvaluate(record.getId());

        EvaluateV2RecordVO result = EvaluateV2RecordVO.of(record);

        return StatusResponse.success(result);

    }

//           4. 测评报告查询：
//              至少可以通过测试报告id，测试报告最后更新时间进行筛选数据。
//              我们会有个定时检查机制，根据最后更新时间，定时去同步你们测试报告的最新状态，报告结果。
//              （最主要需要有测试报告id，测试报告状态，测试时间，其中测试时间用于排行计算）

    @RequestMapping(value = "/report_info", method = POST)
    @ApiOperation(value = "报告对象查询")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "formData", name = "pUserId", value = "当前用户在系统内id", required = true, dataType = "string"),
//            @ApiImplicitParam(paramType = "formData", name = "reportId", value = "报告id", required = true, dataType = "string")
//    })
    public StatusResponse reportInfo(@RequestHeader(PARTNERID_KEY) String partner,
                                     @RequestHeader(AUTH_KEY) String auth,
                                     @RequestHeader(REQ_UUID_KEY) String uuid,
                                     @RequestHeader(COMP_VERSION_KEY) String compver,
                                     String pUserId,
                                     String reportId){

        Staff staff = staffService.maUserByPartnerUserId(pUserId);
        if (staff == null){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "员工不存在");
        }

        EvaluateV2Record object = evaluateService.getEvaluateDetail(reportId);

        return StatusResponse.success(object);
    }

//            5. 测评师需要使用测评工具，跳转到你们测评工具的方式，以及对应的参数（最好只传递一个幼儿id，你们就可以加载出幼儿相关信息以及家长信息）

    @RequestMapping(value = "/report_count", method = GET)
    @ApiOperation(value = "报告数量统计")
    public StatusResponse reportCount(/*@RequestHeader(PARTNERID_KEY) String partner,
                                      @RequestHeader(AUTH_KEY) String auth,
                                      @RequestHeader(REQ_UUID_KEY) String uuid,
                                      @RequestHeader(COMP_VERSION_KEY) String compver,*/
                                      String date,
                                      String mobile){

        List<Staff> staffs = staffService.getByPhone(mobile, null, null);
        if (staffs == null | staffs.size() == 0){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "员工不存在");
        }

        List<String> ids = staffs.stream().map(k->k.getId()).collect(Collectors.toList());

        Date d = null;
        if (StringUtils.isNotEmpty(date)){
            d = DateUtil.parseToDate(date);
        }
        Integer count = evaluateService.countReportsByStaffIds(ids, d);

        return StatusResponse.success(count);
    }


    @RequestMapping(value = "/children_count", method = GET)
    @ApiOperation(value = "报告数量统计")
    public StatusResponse childrenCount(String date, String mobile){

        List<Staff> staffs = staffService.getByPhone(mobile, null, null);
        if (staffs == null | staffs.size() == 0){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "员工不存在");
        }

        List<String> ids = staffs.stream().map(k->k.getId()).collect(Collectors.toList());

        Date d = null;
        if (StringUtils.isNotEmpty(date)){
            d = DateUtil.parseToDate(date);
        }
        Integer count = childrenService.countChildrenByStaffIds(ids, d);

        return StatusResponse.success(count);
    }
//            5. 测评师需要使用测评工具，跳转到你们测评工具的方式，以及对应的参数（最好只传递一个幼儿id，你们就可以加载出幼儿相关信息以及家长信息）



}
